﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using System.Text.RegularExpressions;

namespace Meraz.Core.Parsers
{
    public interface ITweetValuesParser
    {
        bool Parse(TweetValues values);
        void ParseClient(TweetValues values);
    }
    public class TweetValuesParser : ITweetValuesParser
    {
        const string ANCHOR_WITH_ATTRIBUTES_PATTERN = @"(?<AT>[\Wviart\s]+@)?<a.*?class=""(?<CLASS>.+?)"".*?>(?<TEXT>.*?)</a";
        const string ANCHOR_PATTERN = @"</?a[^>]*>";
        Regex ANCHOR_WITH_ATTRIBUTES_REGEX = new Regex(ANCHOR_WITH_ATTRIBUTES_PATTERN, RegexOptions.IgnoreCase);
        Regex ANCHOR_REGEX = new Regex(ANCHOR_PATTERN, RegexOptions.IgnoreCase);

        public bool Parse(TweetValues values)
        {
            if (string.IsNullOrWhiteSpace(values.Text))
                return false;
            values.Links = new List<string>();
            values.Tags = new List<string>();
            values.Mentions = new List<TwitterMention>();
            int mentionSequence = 0;
            foreach (Match match in ANCHOR_WITH_ATTRIBUTES_REGEX.Matches(values.Text))
            {
                if (match.Success)
                {
                    string[] classes = match.Groups["CLASS"].Value.Split();
                    string text = match.Groups["TEXT"].Value;
                    string at = match.Groups["AT"].Value;

                    if (classes.Contains("web", StringComparer.InvariantCultureIgnoreCase))
                    {
                        values.Links.Add(text);
                    }
                    else if (classes.Contains("username", StringComparer.InvariantCultureIgnoreCase))
                    {
                        TwitterMention mention = new TwitterMention();
                        mention.TweetID = values.TweetID;
                        mention.Name = text;
                        mention.Sequence = ++mentionSequence;
                        if (!string.IsNullOrWhiteSpace(at))
                        {
                            mention.IsRetweet = at.ToLower().Contains("rt");
                            mention.IsVia = at.ToLower().Contains("via");
                        }
                        values.Mentions.Add(mention);
                    }
                    else if (classes.Contains("hashtag", StringComparer.InvariantCultureIgnoreCase))
                    {
                        values.Tags.Add(text.TrimStart('#'));
                    }
                }
            }
            values.Text = ANCHOR_REGEX.Replace(values.Text, "");

            return true;
        }

        public void ParseClient(TweetValues values)
        {
            string source = values.Source.Replace("&lt;", "<");
            source = source.Replace("&gt;", ">");
            values.ClientName = ANCHOR_REGEX.Replace(source, "");
        }
    }
}
